//
//  ResetPasswordViewController.m
//  JinYong_iOS_Store
//
//  Created by 王厚一 on 2017/10/18.
//  Copyright © 2017年 why. All rights reserved.
//

#import "ResetPasswordViewController.h"

@interface ResetPasswordViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UILabel *topTitle;//标题

@property(nonatomic,strong)UITextField *phone;//手机号验证码
@property(nonatomic,strong)UITextField *code;

@property (nonatomic, strong) UITextField * firstPass;//两次密码
@property (nonatomic, strong) UITextField * secondPass;

@property(nonatomic,strong)UIButton *VerificationBtn;//获取验证码和提交
@property(nonatomic,strong)UIButton *submitButton;

@property (nonatomic, strong) CAGradientLayer * gradientLayer;//渐变色

@end

@implementation ResetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    //添加Navigation和UI
    [self setupNavigationItem];
    [self setUI];
}

#pragma mark - -------------------------导航条部分----------------------------
-(void)setupNavigationItem{
    
    UIView * topView = ({
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(ActualW(0), ActualH(0), ActualW(375), ActualH(64))];
        view.backgroundColor = RGB(255, 255, 255);
        view;
    });
    [self.view addSubview:topView];
    
    UIImageView * backImage = ({
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(ActualW(10), ActualH(33.5), ActualW(11), ActualH(14))];
        imageView.image = [UIImage imageNamed:@"topback"];
        imageView;
    });
    [topView addSubview:backImage];
    
    UIButton * backButton = ({
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(ActualW(0), ActualH(13.5), ActualW(41), ActualH(44))];
        [button addTarget:self action:@selector(leftButtonClick) forControlEvents:UIControlEventTouchUpInside];
        button;
    });
    [topView addSubview:backButton];

    self.topTitle = ({
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake((SCREENWidth-ActualW(100))/2, ActualH(20), ActualW(100), ActualH(44))];
        label.textColor = RGB(51, 51, 51);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"忘记密码";
        label.font = FontX(FONTSIZE(18));
        label;
    });
    [topView addSubview:self.topTitle];
    
}

- (void)leftButtonClick {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - -------------------------视图部分----------------------------
-(void)setUI{
    UIView * breakView = ({
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(ActualW(0), ActualH(63.5), ActualW(375), ActualH(10))];
        view.backgroundColor = RGB(240, 240, 240);
        view;
    });
    [self.view addSubview:breakView];
    
    //手机号 验证码
    self.phone = ({
        UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake(ActualW(100.5), ActualH(84.5), SCREENW - ActualW(100.5), ActualH(21.5))];
        textField.placeholder = @"请输入11位有效手机号码";
        textField.textColor = RGB(51, 51, 51);
        textField.delegate = self;
        textField.font = FontX(FONTSIZE(14));
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.returnKeyType = UIReturnKeyDone;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.enablesReturnKeyAutomatically = YES;
        textField.leftViewMode = UITextFieldViewModeAlways;
        [textField addTarget:self action:@selector(returnOnKeyboard:) forControlEvents:UIControlEventEditingChanged];
        textField;
    });
    [self.view addSubview:self.phone];
    
    self.code = ({
        UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake(ActualW(100.5), ActualH(129.5), SCREENW - ActualW(220.5), ActualH(21.5))];
        textField.placeholder = @"请输入验证码";
        textField.textColor = RGB(51, 51, 51);
        textField.delegate = self;
        textField.font = FontX(FONTSIZE(14));
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.returnKeyType = UIReturnKeyDone;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.enablesReturnKeyAutomatically = YES;
        textField.leftViewMode = UITextFieldViewModeAlways;
        [textField addTarget:self action:@selector(returnOnKeyboard:) forControlEvents:UIControlEventEditingChanged];
        textField;
    });
    [self.view addSubview:self.code];

    self.VerificationBtn = ({
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(ActualW(256), ActualH(130), ActualW(109), ActualH(21.5))];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [button addTarget:self action:@selector(verificationAction) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:@"发送验证码" forState:UIControlStateNormal];
        [button setTitleColor:RGB(102, 102, 102) forState:UIControlStateNormal];
        button.titleLabel.font = FontX(FONTSIZE(12));
        button;
    });
    [self.view addSubview:self.VerificationBtn];
    
    UIView * breakView2 = ({
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(ActualW(0), ActualH(160), ActualW(375), ActualH(10))];
        view.backgroundColor = RGB(240, 240, 240);
        view;
    });
    [self.view addSubview:breakView2];
    
    //两次密码
    self.firstPass = ({
        UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake(ActualW(100.5), ActualH(181), SCREENW - ActualW(100.5), ActualH(21.5))];
        textField.placeholder = @"请输入密码";
        textField.textColor = RGB(51, 51, 51);
        textField.delegate = self;
        textField.font = FontX(FONTSIZE(14));
        textField.keyboardType = UIKeyboardTypeDefault;
        textField.returnKeyType = UIReturnKeyDone;
        textField.secureTextEntry = YES;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.enablesReturnKeyAutomatically = YES;
        textField.leftViewMode = UITextFieldViewModeAlways;
        [textField addTarget:self action:@selector(returnOnKeyboard:) forControlEvents:UIControlEventEditingChanged];
        textField;
    });
    [self.view addSubview:self.firstPass];
    
    self.secondPass = ({
        UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake(ActualW(100.5), ActualH(224.5), SCREENW - ActualW(100.5), ActualH(21.5))];
        textField.placeholder = @"请重新输入新密码";
        textField.textColor = RGB(51, 51, 51);
        textField.delegate = self;
        textField.font = FontX(FONTSIZE(14));
        textField.keyboardType = UIKeyboardTypeDefault;
        textField.returnKeyType = UIReturnKeyDone;
        textField.secureTextEntry = YES;
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.enablesReturnKeyAutomatically = YES;
        textField.leftViewMode = UITextFieldViewModeAlways;
        [textField addTarget:self action:@selector(returnOnKeyboard:) forControlEvents:UIControlEventEditingChanged];
        textField;
    });
    [self.view addSubview:self.secondPass];
    
    UIView * backView = ({
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(ActualW(0), ActualH(256.5), ActualW(375), ActualH(410.5))];
        view.backgroundColor = RGB(240, 240, 240);
        view;
    });
    [self.view addSubview:backView];
    
    self.submitButton = ({
        UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(ActualW(10),ActualH(25),ActualW(355),ActualH(40))];
        [button addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
        button.enabled = NO;
        [button setTitleColor:RGB(192, 192, 192) forState:UIControlStateNormal];
        button.titleLabel.font = FontX(FONTSIZE(18));
        //初始化CAGradientlayer对象，使它的大小为UIView的大小
        self.gradientLayer = [CAGradientLayer layer];
        self.gradientLayer.frame = button.bounds;
        self.gradientLayer.cornerRadius = ActualW(4);
        //将CAGradientlayer对象添加在我们要设置背景色的视图的layer层
        [button.layer addSublayer:self.gradientLayer];
        //设置渐变区域的起始和终止位置（范围为0-1）
        self.gradientLayer.startPoint = CGPointMake(0, 0);
        self.gradientLayer.endPoint = CGPointMake(1, 0);
        //设置颜色数组
        self.gradientLayer.colors = @[(__bridge id)RGB(192, 192, 192).CGColor, (__bridge id)RGB(192, 192, 192).CGColor];
        //设置颜色分割点（范围：0-1）
        self.gradientLayer.locations = @[@(0.0f), @(1.0f)];
        button;
    });
    [backView addSubview:self.submitButton];
    
    UILabel * denglu = ({
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(ActualW(0), ActualH(0), ActualW(355), ActualH(40))];
        label.textColor = RGB(255, 255, 255);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"提交";
        label.font = FontX(FONTSIZE(18));
        label.backgroundColor = [UIColor clearColor];
        label;
    });
    [self.submitButton addSubview:denglu];
    
    UIView * breakLine = ({
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(ActualW(10), ActualH(116.5), ActualW(355), ActualH(0.5))];
        view.backgroundColor = RGB(220, 220, 220);
        view;
    });
    
    UIView * breakLine2 = ({
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(ActualW(10), ActualH(213), ActualW(355), ActualH(0.5))];
        view.backgroundColor = RGB(220, 220, 220);
        view;
    });
    
    [self.view addSubview:breakLine];
    [self.view addSubview:breakLine2];
    
    UILabel * label = ({
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(ActualW(10), ActualH(88), ActualW(44), ActualH(14))];
        label.textColor = RGB(73, 73, 73);
        label.text = @"手机号";
        label.backgroundColor = RGB(255, 255, 255);
        label.textAlignment = NSTextAlignmentLeft;
        label.font = FontX(FONTSIZE(14));
        label;
    });
    [self.view addSubview:label];
    
    UILabel * label2 = ({
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(ActualW(10), ActualH(133), ActualW(44), ActualH(14))];
        label.textColor = RGB(73, 73, 73);
        label.text = @"验证码";
        label.backgroundColor = RGB(255, 255, 255);
        label.textAlignment = NSTextAlignmentLeft;
        label.font = FontX(FONTSIZE(14));
        label;
    });
    [self.view addSubview:label2];
    
    UILabel * label3 = ({
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(ActualW(10), ActualH(184.5), ActualW(44), ActualH(14))];
        label.textColor = RGB(73, 73, 73);
        label.text = @"新密码";
        label.backgroundColor = RGB(255, 255, 255);
        label.textAlignment = NSTextAlignmentLeft;
        label.font = FontX(FONTSIZE(14));
        label;
    });
    [self.view addSubview:label3];
    
    UILabel * label4 = ({
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(ActualW(10), ActualH(228), ActualW(60), ActualH(14))];
        label.textColor = RGB(73, 73, 73);
        label.text = @"确认密码";
        label.backgroundColor = RGB(255, 255, 255);
        label.textAlignment = NSTextAlignmentLeft;
        label.font = FontX(FONTSIZE(14));
        label;
    });
    [self.view addSubview:label4];
}



#pragma mark - -------------------------获取验证码----------------------------
-(void)verificationAction{
    if (!(_phone.text.length==11)) {
        kShowText(@"输入长度不正确")
        return;
    }
    
    [[URLFather sharedInstance] getResetCodeWithMobile:self.phone.text success:^(NSDictionary *result) {
        if ([Pub resultSuccess:result]) {
            kShowText(@"验证码已发送");
            [self getStartTime];
        }else{
            kShowText(@"获取验证阿妈失败");
        }
    } failure:^(NSError *error) {
        kShowError(@"请求失败");
    }];
}

-(void)getStartTime{
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [_VerificationBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
                _VerificationBtn.userInteractionEnabled = YES;
                
            });
            
        }else{
            int seconds = timeout % 61;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_VerificationBtn setTitle:[NSString stringWithFormat:@"%@S",strTime] forState:UIControlStateNormal];
                _VerificationBtn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
}

#pragma mark - -------------------------提交----------------------------
- (void)submitAction {
    if (![self.firstPass.text isEqualToString:self.secondPass.text]) {
        kShowText(@"两次输入密码不一致");
        return;
    }
    [[URLFather sharedInstance] resetPasswdWithMobile:self.phone.text code:self.code.text passwd:self.firstPass.text success:^(NSDictionary *result) {
        if ([Pub resultSuccess:result]) {
            kShowSuccess(@"重置密码成功");
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            kShowText(result[@"msg"]);
        }
    } failure:^(NSError *error) {
        kShowError(@"请求失败");
    }];

}

#pragma mark - -------------------------检测是否可以提交--------------------------
-(void)check{
    
    if (self.phone.text.length > 0 && self.code.text.length > 0 && self.firstPass.text.length > 0 && self.secondPass.text.length > 0) {
        self.gradientLayer.colors = @[(__bridge id)RGB(82, 137, 240).CGColor, (__bridge id)RGB(86, 176, 224).CGColor];
        self.submitButton.enabled=YES;
    }else{
        self.gradientLayer.colors = @[(__bridge id)RGB(192, 192, 192).CGColor, (__bridge id)RGB(192, 192, 192).CGColor];
        self.submitButton.enabled=NO;
    }
    
    
}


#pragma mark - --------------------------键盘操作---------------------------
-(void)hidenKeyboard{
    [self.phone resignFirstResponder];
    [self.code resignFirstResponder];
    [self.firstPass resignFirstResponder];
    [self.secondPass resignFirstResponder];
}

- (void)returnOnKeyboard:(UITextField *)sender
{
    if (self.phone.text.length != 0 && self.code.text.length !=0 && self.firstPass.text.length != 0 && self.secondPass.text.length != 0) {
        self.submitButton.enabled = YES;
    } else {
        self.submitButton.enabled = NO;
    }
    
    [self check];
}

-(void)textFieldDidChange:(UITextField *)textField{
    [self check];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField == self.phone) {
        return [self.code becomeFirstResponder];
    }else if(textField == self.code) {
        return [self.firstPass becomeFirstResponder];
    }else if (textField == self.firstPass) {
        return [self.secondPass becomeFirstResponder];
    }else {
        [self hidenKeyboard];
        return [self.secondPass resignFirstResponder];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
